package mgoDB

import (
	"reflect"
	"strconv"
	"time"

	"go.mongodb.org/mongo-driver/mongo"
)

//MgoContent 数据库上下文
type MgoContent struct {
	database     *mongo.Database
	databaseName string
	timeout      time.Duration
}

//DataBaseMapping 添加映射
// @client 连接对象
// @dataName 数据库名
func DataBaseMapping(config map[string]string) (*MgoContent,error) {
	dbname := config["dbname"]
	timeout := time.Second * 30
	if timeoutStr, ok := config["timeout"]; ok {
		atoi, err := strconv.Atoi(timeoutStr)
		if err == nil {
			timeout = time.Second * time.Duration(atoi)
		}
	}

	client, err := GetMgoClient(config)
	if err != nil {
		return nil, err
	}
	database := client.Database(dbname)
	return &MgoContent{
		database:     database,
		databaseName: dbname,
		timeout:      timeout,
	},nil
}

//GetCollection 获取集合
func (m *MgoContent) GetCollection(entity interface{}) *CollectionContent {
	var entityName string
	typeOfCat := reflect.TypeOf(entity)
	if typeOfCat.Kind() == reflect.Ptr {
		entityName = typeOfCat.Elem().Name()
	}else {
		entityName = typeOfCat.Name()
	}
	return &CollectionContent{
		database:       m.database,
		databaseName:   m.databaseName,
		collection:     m.database.Collection(entityName),
		collectionName: entityName,
	}
}

//GetMgoRepository 获取集合仓储
// entity 结构体
func (m *MgoContent) GetMgoRepository(entity interface{}) IMgoRepository {
	var entityName string
	typeOfCat := reflect.TypeOf(entity)
	if typeOfCat.Kind() == reflect.Ptr {
		entityName = typeOfCat.Elem().Name()
	} else {
		entityName = typeOfCat.Name()
	}
	collectionContent := &CollectionContent{
		database:       m.database,
		databaseName:   m.databaseName,
		collection:     m.database.Collection(entityName),
		collectionName: entityName,
	}
	return &MgoRepository{collectionContent, m.timeout}
}
